package com.kaifamiao.reqeust;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;

public class UploadSingleServlet extends HttpServlet {

    private String savePath;

    @Override
    public void init() throws ServletException {
        savePath = this.getInitParameter( "savePath" );
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new ServletException( "不支持以GET方式上传文件" );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();

        // <input type="file" name="upfile">
        Part part = request.getPart( "upfile" ); // Servlet 3.0
        if( part == null ) {
            out.println( "<p>表单控件名称错误</p>" );
            out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
            return;
        }

        // 获得用户上传的原始文件名称
        String fileName = part.getSubmittedFileName(); // Servlet 3.1
        // 若文件名是空字符串则表示用户没有选择文件
        if( fileName.isEmpty() ) {
            out.println( "<p>请选择需要上传的文件后再点击上传</p>" );
            out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
            return;
        }

        String uuid = UUID.randomUUID().toString().toUpperCase();
        uuid = uuid.replace( "-" , "" );

        int index = fileName.lastIndexOf( '.' );
        fileName = index == -1
                    ?
                    fileName + "_" + uuid
                    :
                    fileName.substring(0,index) + "_" + uuid + fileName.substring(index);

        File target = new File( savePath, fileName );

        try {
            InputStream in = part.getInputStream();
            OutputStream os = new FileOutputStream( target );
            in.transferTo( os ); // Java 9
            out.printf( "<p>文件[%s上]传成功</p>", fileName );
            out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
            os.close();
            in.close();
        } catch ( IOException e ) {
            out.printf( "<p>文件[%s]上传失败</p>" , fileName );
            out.printf( "<p>%s: %s</p>" , e.getClass().getName(), e.getMessage() );
            out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
        }

    }

}
